const express = require('express');
const im = express.Router();
const connection = require("../config");
const moment = require('moment');

im.post('/im/list', (req, res) => {
    //查询语句
    const {uid, bridge} = req.body;
    let sql = `select * from im where 1=1 and bridge='${bridge}' order by id asc`
    connection.query(`${sql}`, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR]:', err.message);
        }
        if(result.length) {
            result.forEach(item => {
                item.bridge = bridge.split(',')
            });
        }
        res.send({data:result, status: result.length ? 1 : 0}) //数据库查询结果返回到result中,把查询数据发送到客户端
    });
})

im.post('/im/save', (req, res) => {
    const {uid, nickname,msg,bridge} = req.body;
    const insertsql = `insert into im (uid, nickname,msg,bridge, date) values(?,?,?,?,?)`
    console.log(uid, nickname,msg, bridge,moment().format('YYYY-MM-DD HH:mm:ss'))
    connection.query(insertsql, [uid, nickname,msg, bridge,moment().format('YYYY-MM-DD HH:mm:ss')], (errs, results) => {
        console.log(results)
        if (errs) {
            console.log('[SELECT ERROR]:', errs.message);
            return;

        }
        res.send({
            status: 1,
            msg: "保存成功！"
        })
    })
})

module.exports = im;